package com.zx.znav.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zx.znav.bean.Link;
import com.zx.znav.bean.LinkTag;
import com.zx.znav.bean.Tag;
import com.zx.znav.constant.Constants;
import com.zx.znav.controller.vo.LinkVO;
import com.zx.znav.service.LinkService;
import com.zx.znav.service.LinkTagService;
import com.zx.znav.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 根据标签展示链接
 * @since 2023-07-26 7:06
 */
@Controller
@RequestMapping("/tag")
public class ShowTagController {
    @Autowired
    private TagService tagService;
    @Autowired
    private LinkService linkService;
    @Autowired
    private LinkTagService linkTagService;
    @RequestMapping()
    public String index(Model model){
        render(model, null);
        return "tag";
    }
    //链接详情跳转过来
    @GetMapping("/{id}")
    public String tag(Model model,@PathVariable Integer id){
        render(model, id);
        return "tag";
    }

    /**
     * 加载网页片段
     * @param id 标签id
     */
    @PostMapping("/fragment")
    public String load(Model model, Integer id){
        render(model, id);
        return "tag :: content";
    }
    /**
     * 设置模型数据
     * @param id tagId, 传null,选中第一个
     */
    private void render(Model model, Integer id){
        //查标签
        List<Tag> tags = tagService.listTags();
        model.addAttribute(Constants.TAG_KEY, tags);
        //查第一个标签下的链接
        if(tags.size() > 0){
            Integer tagId = tags.get(0).getId();
            if(id != null) tagId = id;
            model.addAttribute(Constants.TAG_ID, tagId);
            //查其下的链接
            List<LinkTag> linkTagList = linkTagService.listByTagId(tagId);
            List<Integer> linkIds = linkTagList.stream().map(LinkTag::getLinkId).collect(Collectors.toList());
            if(linkIds.size() > 0){
                List<Link> links = linkService.listByIds(linkIds);
                model.addAttribute(Constants.LinKS_KEY, links);
            }
        }
    }
}
